package cn.iocoder.yudao.module.brokerage.user.mq;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.framework.common.exception.Assertions;
import cn.iocoder.yudao.module.api.brokerage.level.enums.BrokerageLevelTypeEnum;
import cn.iocoder.yudao.module.api.brokerage.record.enums.BrokerageRecordBizTypeEnum;
import cn.iocoder.yudao.module.api.brokerage.user.message.BrokerageUserBindMessage;
import cn.iocoder.yudao.module.api.member.agency.message.AgencyOrderPaidMessage;
import cn.iocoder.yudao.module.api.member.agency.message.AgencyUserExpiredMessage;
import cn.iocoder.yudao.module.api.member.agency.vo.AgencyOrderVO;
import cn.iocoder.yudao.module.api.member.user.message.MemberUserCreateMessage;
import cn.iocoder.yudao.module.api.member.user.message.MemberUserInviteMessage;
import cn.iocoder.yudao.module.api.member.vip.enums.VipLevelEnum;
import cn.iocoder.yudao.module.api.member.vip.message.VipOrderPaidMessage;
import cn.iocoder.yudao.module.api.member.vip.message.VipUserExpiredMessage;
import cn.iocoder.yudao.module.api.member.vip.vo.VipOrderVO;
import cn.iocoder.yudao.module.api.trade.order.dto.TradeOrderItemRespDTO;
import cn.iocoder.yudao.module.api.trade.order.dto.TradeOrderRespDTO;
import cn.iocoder.yudao.module.api.trade.order.message.TradeAfterSaleCompletedMessage;
import cn.iocoder.yudao.module.api.trade.order.message.TradeOrderCompletedMessage;
import cn.iocoder.yudao.module.api.trade.order.message.TradeOrderPaidMessage;
import cn.iocoder.yudao.module.api.trade.scan.dto.ScanOrderDTO;
import cn.iocoder.yudao.module.api.trade.scan.message.ScanOrderPaidMessage;
import cn.iocoder.yudao.module.brokerage.record.dao.BrokerageRecordMapper;
import cn.iocoder.yudao.module.brokerage.record.pojo.po.BrokerageRecordDO;
import cn.iocoder.yudao.module.brokerage.record.service.BrokerageRecordService;
import cn.iocoder.yudao.module.brokerage.user.service.AppBrokerageUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 推广用户 事件消费者
 *
 * @author 山野羡民
 */
@Component
@Slf4j
public class BrokerageUserConsumer {

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(MemberUserCreateMessage message) {
        log.info("[brokerage][onMessage][用户创建事件({})]", message);
        SpringUtil.getBean(AppBrokerageUserService.class).getOrCreate(message.getUserId());
    }

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(MemberUserInviteMessage message) {
        log.info("[brokerage][onMessage][新用户邀请事件({})]", message);
        SpringUtil.getBean(AppBrokerageUserService.class).autoSyncRelation(message.getRegisterUserId(), message.getInviteUserId());
    }

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(BrokerageUserBindMessage message) {
        log.info("[brokerage][onMessage][推广关系户绑定事件({})]", message);
        SpringUtil.getBean(AppBrokerageUserService.class).updateWhenBindSuccess(message.getUserId(), message.getFatherUserId());
    }

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(VipUserExpiredMessage message) {
        log.info("[brokerage][onMessage][会员过期事件({})]", message);
        SpringUtil.getBean(AppBrokerageUserService.class).updateLevelWeight(message.getUserId(), BrokerageLevelTypeEnum.NORMAL.getValue(), 0);
    }

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(AgencyUserExpiredMessage message) {
        log.info("[brokerage][onMessage][招商人员过期事件({})]", message);
        SpringUtil.getBean(AppBrokerageUserService.class).updateLevelWeight(message.getUserId(), BrokerageLevelTypeEnum.NORMAL.getValue(), 0);
    }

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(TradeOrderPaidMessage message) {
        TradeOrderRespDTO order = message.getOrder();
        log.info("[brokerage][onMessage][交易订单支付事件({})]", order.getNo());
        SpringUtil.getBean(BrokerageRecordService.class).addBrokerageWhenOrderPaid(order);
    }

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(TradeOrderCompletedMessage message) {
        TradeOrderRespDTO order = message.getOrder();
        log.info("[brokerage][onMessage][交易订单完成事件({})]", order.getNo());
        List<BrokerageRecordDO> records = SpringUtil.getBean(BrokerageRecordMapper.class).selectByBizTypeAndBizId(BrokerageRecordBizTypeEnum.BUY_PRODUCT.getCode(), order.getNo());
        if (CollUtil.isEmpty(records)) {
            log.warn("[brokerage][onMessage][交易订单完成未找到对应的佣金记录：{}", order.getNo());
            return;
        }
        BrokerageRecordService brokerageRecordService = SpringUtil.getBean(BrokerageRecordService.class);
        for (BrokerageRecordDO record : records) {
            brokerageRecordService.unfreezeUserRecord(record);
        }
    }

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(TradeAfterSaleCompletedMessage message) {
        TradeOrderRespDTO order = message.getOrder();
        log.info("[brokerage][onMessage][交易订单售后完成事件({})]", order.getNo());
        TradeOrderItemRespDTO orderItem = message.getOrderItem();
        Assertions.notNull(orderItem, "交易订单售后完成事件携带的订单项信息为空");
        SpringUtil.getBean(BrokerageRecordService.class).cancelBrokerage(order, orderItem);
    }

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(ScanOrderPaidMessage message) {
        ScanOrderDTO order = message.getOrder();
        log.info("[brokerage][onMessage][线下扫码订单支付完成事件({})]", order.getTradeNo());
        SpringUtil.getBean(BrokerageRecordService.class).addBrokerageWhenOrderPaid(order);
        List<BrokerageRecordDO> records = SpringUtil.getBean(BrokerageRecordMapper.class).selectByBizTypeAndBizId(BrokerageRecordBizTypeEnum.OFFLINE_SCAN_ORDER.getCode(), order.getTradeNo());
        if (CollUtil.isEmpty(records)) {
            log.warn("[brokerage][onMessage][线下扫码订单支付完成未找到对应的佣金记录：{}", order.getTradeNo());
            return;
        }
        BrokerageRecordService brokerageRecordService = SpringUtil.getBean(BrokerageRecordService.class);
        for (BrokerageRecordDO record : records) {
            brokerageRecordService.unfreezeUserRecord(record);
        }
    }

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(VipOrderPaidMessage message) {
        log.info("[brokerage][onMessage][会员缴费完成事件({})]", message);
        VipOrderVO order = message.getOrder();
        Assertions.notNull(order, "会员缴费完成事件携带的订单信息为空");
        SpringUtil.getBean(AppBrokerageUserService.class).updateLevelWeight(order.getUserId(), BrokerageLevelTypeEnum.VIP.getValue(), VipLevelEnum.NORMAL.getValue());
        SpringUtil.getBean(BrokerageRecordService.class).addBrokerageWhenOrderPaid(order);
        List<BrokerageRecordDO> records = SpringUtil.getBean(BrokerageRecordMapper.class).selectByBizTypeAndBizId(BrokerageRecordBizTypeEnum.BUY_VIP.getCode(), order.getTradeNo());
        if (CollUtil.isEmpty(records)) {
            log.warn("[brokerage][onMessage][会员缴费完成未找到对应的佣金记录：{}", order.getTradeNo());
            return;
        }
        BrokerageRecordService brokerageRecordService = SpringUtil.getBean(BrokerageRecordService.class);
        for (BrokerageRecordDO record : records) {
            brokerageRecordService.unfreezeUserRecord(record);
        }
    }

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(AgencyOrderPaidMessage message) {
        log.info("[brokerage][onMessage][招商人员入驻缴费完成事件({})]", message);
        AgencyOrderVO order = message.getOrder();
        Assertions.notNull(order, "招商人员入驻缴费完成事件携带的订单信息为空");
        SpringUtil.getBean(AppBrokerageUserService.class).updateLevelWeight(order.getUserId(), BrokerageLevelTypeEnum.AGENCY.getValue(), order.getLevel());
        SpringUtil.getBean(BrokerageRecordService.class).addBrokerageWhenOrderPaid(order);
        List<BrokerageRecordDO> records = SpringUtil.getBean(BrokerageRecordMapper.class).selectByBizTypeAndBizId(BrokerageRecordBizTypeEnum.BUY_AGENCY.getCode(), order.getTradeNo());
        if (CollUtil.isEmpty(records)) {
            log.warn("[brokerage][onMessage][招商人员入驻缴费完成未找到对应的佣金记录：{}", order.getTradeNo());
            return;
        }
        BrokerageRecordService brokerageRecordService = SpringUtil.getBean(BrokerageRecordService.class);
        for (BrokerageRecordDO record : records) {
            brokerageRecordService.unfreezeUserRecord(record);
        }
    }

}
